package com.gykfbxxh.imovie.view.user.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.app.utils.util.ToastUtils;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.BaseActivity;
import com.gykfbxxh.imovie.custom.view.LoadView;
import com.gykfbxxh.imovie.custom.view.web.CustomWebView;

/**
 * 公用的显示网页页面
 * Created by xuxinghai on 2016/7/18.
 */
@SuppressLint("JavascriptInterface")
public class WebActivity extends BaseActivity implements View.OnClickListener {
    /**
     * title名
     */
    private String title;
    /**
     * 加载的url
     */
    private String url;
    private CustomWebView webView;
    private LoadView loadView;

    private boolean isShowPageFinish = true;// 是否展示页面加载完成

    private JavascriptInterface javascriptInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSlideBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
//        addContentView(R.layout.activity_web);
        //setTitleShow(false);
        initView();
        initListener();
        initWebView();
//        Map<String,String> map = new HashMap<>();
//        map.put("referer",URIContant.REALMNAME);
        // 加载URL
        if (!TextUtils.isEmpty(url)) {
//            String night = NightModeHelper.readMode?"1":"0";
//            if(url.contains("?")){
//                url += "&night="+night;
//            }else{
//                url += "?night="+night;
//            }
            webView.loadUrl(url);
            loadView.showSuccess();
        } else {
            loadView.showErrorPage("加载的网址为空");
        }

    }

    private void initListener() {
        loadView.setErrorPageClickListener(this);

    }

    private ProgressBar progressBar;

    /**
     * 初始化页面
     */
    private void initView() {
        getIntentData();
        setTitle("加载中...");
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
        webView = (CustomWebView) findViewById(R.id.webview);
        loadView = (LoadView) findViewById(R.id.loadview);

    }

    @Override
    protected void onStart() {
        super.onStart();
        if(loadView != null){
            loadView.showLoadPage(null);
        }

    }

    private void getIntentData() {
        Intent intent = this.getIntent();
        if (intent == null) return;
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        WebSettings settings = webView.getSettings();
//        settings.setBlockNetworkImage(true);// 延迟图片加载
        settings.setSavePassword(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        // 启动缓存
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        // 设置缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setBackgroundColor(Color.argb(0, 0, 0, 0));
        //手动获取焦点
        webView.setFocusable(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.requestFocus();
        if (Build.VERSION.SDK_INT >= 19) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        javascriptInterface = new JavascriptInterface(WebActivity.this);
        webView.addJavascriptInterface(javascriptInterface, "android");
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if(newProgress==100){
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                }
                else{
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }
            }
        });

    }

    /**
     * js 可调用的方法
     */
    @SuppressLint("JavascriptInterface")
    public class JavascriptInterface {

        private Activity activity;
        private String json;

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if(msg == null){
                    return;
                }
                switch (msg.what){
                    case 0://展示错误界面
                       ToastUtils.makeText(getResources().getString(R.string.neterror));
                        break;
                    case 1://展示分享界面
//                        CustomDialog.getInstance().showShareDialog(activity, onClickInviteListener);
                        break;
                    case 3://修改标题
                        String title = (String) msg.obj;
                        setTitle(title);

                        break;
                    case 4://返回到webview 首页
                        if(webView != null){
                            while(webView.canGoBack()){
                               webView.goBack();
                            }

                        }
                        break;
                }


            };
        };




        public JavascriptInterface(Activity activity) {
            this.activity = activity;
        }

        @android.webkit.JavascriptInterface
        public void getData(String json) {
            this.json = json;
            if(TextUtils.isEmpty(json)){
                Message msg = Message.obtain();
                msg.what = 0;
                handler.sendMessage(msg);
            }else{
                Message msg = Message.obtain();
                msg.what = 1;
                handler.sendMessage(msg);
            }
        }


        //返回json字符串
        public String getJson() {


            if (TextUtils.isEmpty(json)) {
                return "";
            } else {
                return json;
            }
        }

        /**
         * 显示title
         * @param html
         */
        @android.webkit.JavascriptInterface
        public void showSource(String html) {
            Message msg = Message.obtain();
            msg.what = 3;
            msg.obj = html;
            handler.sendMessage(msg);
        }


        @android.webkit.JavascriptInterface
        public void jumpFightCenter(String json){
//            onBackPressed();
//            startActivity(new Intent(WebActivity.this, UserTaskActivity.class));

        }



        @android.webkit.JavascriptInterface
        public void bashOrder(String json){
//            this.json = json;
//            Gson gson = new Gson();
//            try {
//                BashOrder bashOrder = gson.fromJson(json, BashOrder.class);
//                if(bashOrder != null){
//                    Intent intent = new Intent(WebActivity.this, PostSendActivity.class);
////                    intent.putExtra(PARAMETER1,bashOrder.getTopicId());
////                    intent.putExtra(PARAMETER2,bashOrder.getTopicTitle());
//                    intent.putExtra(PARAMETER1,true);
//                    startActivity(intent);
////                    startActivityForResult(intent,REQUESTCODE_1);
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }

        class BashOrder{
            public String topicId;
            public String topicTitle;
            public String getTopicId() {
                return topicId;
            }
            public String getTopicTitle() {
                return topicTitle;
            }

        }


        /**
         * 返回首页
         */
        @android.webkit.JavascriptInterface
        public void exchangeIndex(String json){
            Message msg = Message.obtain();
            msg.what = 4;
            handler.sendMessage(msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置友盟回调
//        try {
//            if(data != null) {
//                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


    }

//
//    /**
//     * 分享弹窗的点击监听
//     */
//    private CustomDialog.OnClickInviteListener onClickInviteListener = new CustomDialog.OnClickInviteListener() {
//        @Override
//        public void qqInvite() {
//            ShareBean shareBean = returnShareBean();
//            AppShareUtils.getInstance().setQQShareContent(WebActivity.this, shareBean,umInviteListener);
//        }
//
//        @Override
//        public void wxInvite() {
//            ShareBean shareBean = returnShareBean();
//            AppShareUtils.getInstance().setWXShareContent(WebActivity.this, shareBean,umInviteListener);
//        }
//
//        @Override
//        public void wxFriendsInvite() {
//            ShareBean shareBean = returnShareBean();
//            AppShareUtils.getInstance().setWXCShareContent(WebActivity.this, shareBean,umInviteListener);
//        }
//    };




//    /**
//     * 邀请后的回调
//     */
//    public UMShareListener umInviteListener = new UMShareListener() {
//        @Override
//        public void onResult(SHARE_MEDIA platform) {
//            ToastUtils.makeText(R.drawable.handle_success,"分享成功");
//
//            StatisticInvite(platform);
//            StatService.onEvent(mActivity, "010", "邀请好友成功", 1);//统计事件的点击次数
//
//        }
//
//        @Override
//        public void onError(SHARE_MEDIA platform, Throwable t) {
//            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
//            StatService.onEvent(mActivity, "011", "邀请好友失败", 1);//统计事件的点击次数
//        }
//
//        @Override
//        public void onCancel(SHARE_MEDIA platform) {
//            ToastUtils.makeText("分享取消");
//        }
//
//    };

//    /**
//     * 统计邀请次数
//     * @param platform  平台号
//     */
//    private void StatisticInvite(SHARE_MEDIA platform) {
//        if(platform == null){
//            ToastUtils.makeText(R.drawable.handle_fail,"分享失败");
//            return;
//        }
//        ParamMap param = new ParamMap();
//        String type = "0";
//        if(SHARE_MEDIA.SINA.equals(platform.toSnsPlatform().mPlatform)){
//            type = "1";
//        }else if(SHARE_MEDIA.WEIXIN.equals(platform.toSnsPlatform().mPlatform)){
//            type = "2";
//        }else if(SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform.toSnsPlatform().mPlatform)){
//            type = "3";
//        }else if(SHARE_MEDIA.QQ.equals(platform.toSnsPlatform().mPlatform)){
//            type = "4";
//        }else if(SHARE_MEDIA.QZONE.equals(platform.toSnsPlatform().mPlatform)){
//            type = "5";
//        }else {
//            type = "0";
//        }
//        param.putEncode("channelType",type);
//        if(UserInforManager.getInstance() != null){
//            param.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
//        }else{
//            param.putEncode("uid", "");
//        }
//        HttpUtils.ParmsMapMD5(param);
//
//        addPostRequest(URIContant.INVITE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
//        }.getType(), param, httpListener);
//    }

//   private HttpListener httpListener =  new HttpListener<DataBean<GetTaskBean>>() {
//        @Override
//        public void onError(VolleyError error) {
//
//        }
//
//        @Override
//        public void onSuccess(DataBean<GetTaskBean> response) {
//            if(response.noError() && response.getData() != null
//                    && response.getData().getIsGetTask("邀请好友")){
//                //刷新任务
//                UserInforManager.getInstance().getUserTask(mActivity,false);
//
//            }
//        }
//    };


//    /**
//     * 返回一个shareBean
//     * @return
//     */
//    private ShareBean returnShareBean() {
//        ShareBean shareBean = null;
//        if (javascriptInterface == null) {
//            javascriptInterface = new JavascriptInterface(WebActivity.this);
//        }
//        String json = javascriptInterface.getJson();
//        Gson gson = new Gson();
//        try {
//            shareBean = gson.fromJson(json, ShareBean.class);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return shareBean;
//    }


    // 监听
    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
//            super.onReceivedSslError(view, handler, error);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(TextUtils.isEmpty(url) || url.length() < 5) {
                return false;
            }
            //判断是否为http协议，如果是自定义协议则交给系统
            String httpStr = "";
            try {
                httpStr = url.substring(0, 4);
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
            if (!TextUtils.isEmpty(httpStr) && !httpStr.equals("http")
                    && !httpStr.equals("https")&& !httpStr.equals("abou")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }else if(httpStr.equals("abou")) {
                return true;
            }else {
                if (view != null){
                    view.loadUrl(url);
                }
                return true;
            }




        }

        @Override
        public void onPageFinished(final WebView view, String url) {
//            view.getSettings().setBlockNetworkImage(false);// 取消延迟加载

            if (isShowPageFinish) {
                isShowPageFinish = false;
                if(!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
                view.loadUrl("javascript:window.android.showSource('"+view.getTitle()+"');");
                loadView.showSuccess();
            }

        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            if (url != null && url.equals(failingUrl)) {


                loadView.setVisibility(View.VISIBLE);
                loadView.showErrorPage();
                isShowPageFinish = false;
            }
            super.onReceivedError(view, errorCode, description, failingUrl);


        }
    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.error_page://loadview的错误页面ID
                //刷新
                if (TextUtils.isEmpty(url)) {
                    ToastUtils.showText("加载的网址为空");
                    return;
                }
                if (webView == null) {
                    return;
                }
                webView.clearHistory();
                isShowPageFinish = true;
                if(loadView != null){
                    loadView.showLoadPage(null);
                }

                webView.loadUrl(url);
                break;
        }


    }



    @Override
    public void doBack(View view) {
        long currentTime = System.currentTimeMillis();
        //如果连续点击的时间小于 MIN_CLICK_DELAY_TIME  则本次点击不起效
        if (currentTime - lastClickTime > 500) {
            lastClickTime = currentTime;
            if(webView != null && webView.canGoBack()){
                webView.goBack();
            }else{
                onBackPressed();
            }

        }
    }

    @Override
    public boolean
    onKeyDown(int keyCode, KeyEvent event) {
        if (event == null)
            return true;// 防止nullException
        if (keyCode == KeyEvent.KEYCODE_BACK
                && webView != null && webView.canGoBack()) {
            //如果当前网页能返回则网页后退
            webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}
